package com.toy.mforum.web.admin;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.toy.base.domain.User;
import com.toy.base.service.UserManager;
import com.toy.core.dao.support.Page;
import com.toy.core.util.LabelValue;
import com.toy.core.util.StringUtils;

@Controller
@RequestMapping("/admin/user")
public class AdminUserController {
	
	@Autowired
	private UserManager userManager;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}	

	
	
	//用户列表
	@RequestMapping("/findUserPaged")
	public String findUserPaged(String pageNo,String pageSize,Model model){
		int _pageNo = StringUtils.parseString(pageNo, 1);
		int _pageSize = StringUtils.parseString(pageSize, 2);
		Page<User> page = userManager.findPaged(_pageNo, _pageSize);
		model.addAttribute("page", page);
		return "/mforum/admin/user/list_users";
	}
	
	//新增用户
	@RequestMapping("/newUser")
	public String newUser(Model model){
		Collection<LabelValue> userStateValues = User.getUserStateValues();
		model.addAttribute("userStateValues", userStateValues);
		return "/mforum/admin/user/edit_user";
	}
	
	//编辑用户
	@RequestMapping("/editUser/{userId}")
	public String editUser(@PathVariable String userId,Model model){
		Collection<LabelValue> userStateValues = User.getUserStateValues();
		model.addAttribute("userStateValues", userStateValues);
		if (StringUtils.isNotEmpty(userId)){
			User user = userManager.getById(Long.valueOf(userId));
			model.addAttribute("user", user);
		}
		return "/mforum/admin/user/edit_user";
	}
	
	//保存用户
	@RequestMapping("/saveOrUpdateUser")
	public String saveOrUpdateUser(User user,Model model) throws Exception{
		if ( user.getId() > 0 ){
			User _user = userManager.getById(user.getId());
			PropertyUtils.copyProperties(_user, user);
			userManager.saveOrUpdate(_user);
		}else{
			user.setRegDate(new Date());
			userManager.saveOrUpdate(user);
		}
		return "redirect:/admin/user/findUserPaged";
	}
	
}
